package com.aat.restful.springmvc.netty.channel;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

import javax.servlet.ServletException;

import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import com.aat.restful.springmvc.netty.handler.ServletHandler;

/**
 *
 * @ClassName: DispatcherServletChannelInitializer
 * @Description: 服务启动控制器
 * @version V1.0
 *
 */
public class DispatcherServletChannelInitializer extends ChannelInitializer<SocketChannel> {

	private final DispatcherServlet dispatcherServlet;

	private final String charset;

	/**
	 * 构造器，初始化上下文
	 * 
	 * @param charset
	 * @param env
	 * @param configLocation
	 * @throws ServletException
	 */
	public DispatcherServletChannelInitializer(String charset, String... configLocation) throws ServletException {
		this.charset = charset;

		MockServletContext servletContext = new MockServletContext();
		MockServletConfig servletConfig = new MockServletConfig(servletContext);

		XmlWebApplicationContext wac = new XmlWebApplicationContext();
		wac.setServletContext(servletContext);
		wac.setServletConfig(servletConfig);
		wac.setConfigLocations(configLocation);
		this.dispatcherServlet = new DispatcherServlet(wac);
		this.dispatcherServlet.init(servletConfig);
	}

	protected void initChannel(SocketChannel socketChannel) throws Exception {
		ChannelPipeline pipeline = socketChannel.pipeline();
		pipeline.addLast("decoder", new HttpRequestDecoder());
		pipeline.addLast("encoder", new HttpResponseEncoder());
		pipeline.addLast("aggregator", new HttpObjectAggregator(65536));

		pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
		// pipeline.addLast("deflater",new HttpContentCompressor());

		pipeline.addLast("handler", new ServletHandler(dispatcherServlet, charset));
	}

}
